//
//  UserLocationController.swift
// 家庭位置管理
//  home
//
//  Created by Yun Zeng on 2019/9/23.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit
import MapKit

class UserHomeController: UIViewController {
    
    private lazy var customBar: CustomNavigationBar = {
        let bar = CustomNavigationBar()
        bar.title = "云の家"
        bar.subtitle = "金成时代家园"
        bar.icon = UIImage(named: "user-settings-home")
        return bar
    } ()
    
    private lazy var userRegionIdentifier: String = {
        let home = HomeManager.instance.current!
        return "adai.design.home." + home.id
    } ()
    
    private lazy var userRegionName: String = {
        let home = HomeManager.instance.current!
        return home.name
    } ()
    
    let locationManager = CLLocationManager()
    var monitoredRegions: Dictionary<String, Date> = [:]
    
    private lazy var mapView: MKMapView = {
        let map = MKMapView()
        return map
    }()
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hex: "dedede")
        self.view.addSubview(self.customBar)
        customBar.translatesAutoresizingMaskIntoConstraints = false
        customBar.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        customBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        customBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        customBar.cancel = {
            self.dismiss(animated: true, completion: nil)
        }
        
        let attributes: [NSAttributedString.Key : Any] = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium),
            NSAttributedString.Key.foregroundColor: UIColor(red: 0, green: 0, blue: 0, alpha: 1),
            NSAttributedString.Key.kern: -0.51]

        let mapTitle = UILabel()
        mapTitle.attributedText = NSAttributedString(string: "位置", attributes: attributes)
        self.view.addSubview(mapTitle)
        mapTitle.translatesAutoresizingMaskIntoConstraints = false
        mapTitle.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
        mapTitle.heightAnchor.constraint(equalToConstant: 22).isActive = true
        mapTitle.topAnchor.constraint(equalTo: self.customBar.bottomAnchor, constant: 17).isActive = true
        
        // 地图设置
        self.view.addSubview(self.mapView)
        mapView.translatesAutoresizingMaskIntoConstraints = false
        mapView.topAnchor.constraint(equalTo: mapTitle.bottomAnchor, constant: 14).isActive = true
        mapView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 15).isActive = true
        mapView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15).isActive = true
        mapView.heightAnchor.constraint(equalToConstant: 345).isActive = true
        mapView.layer.cornerRadius = 12
        mapView.layer.masksToBounds = true
        mapView.layer.borderWidth = 0.5
        mapView.layer.borderColor = UIColor.white.cgColor
        
    
        mapView.delegate = self
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .follow
        
        // 地理围栏设置
        locationManager.delegate = self
        locationManager.distanceFilter = 100
        locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        
        // 设置地理围栏
        self.setUpData()
        
        // 打印地理围栏信息
        for region in locationManager.monitoredRegions {
            Logger.Info("monitoring region: \(region.identifier) notifyOnEntry: \(region.notifyOnEntry) notifyOnExit: \(region.notifyOnExit)")
            if region.identifier == "adai.design.home187c7894-1d3d-442b-9d3a-d2ebcfa86a6c" {
                locationManager.stopMonitoring(for: region)
            }
        }
        
        // 家庭成员
        let membersTitle = UILabel()
        membersTitle.attributedText = NSAttributedString(string: "家庭成员", attributes: attributes)
        self.view.addSubview(membersTitle)
        membersTitle.translatesAutoresizingMaskIntoConstraints = false
        membersTitle.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = true
        membersTitle.heightAnchor.constraint(equalToConstant: 22).isActive = true
        membersTitle.topAnchor.constraint(equalTo: self.mapView.bottomAnchor, constant: 25).isActive = true
        
        // 家庭成员
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalCentering
        stackView.spacing = 12
        stackView.alignment = .trailing
        stackView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: membersTitle.bottomAnchor, constant: 15).isActive = true
        stackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 18).isActive = true
        
        let membership = UserInfoView(name: "了结大师", head: "user-head", state: "(离家)")
        stackView.addArrangedSubview(membership)
        membership.translatesAutoresizingMaskIntoConstraints = false
        membership.widthAnchor.constraint(equalToConstant: 70).isActive = true
        membership.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
        
        let membershipAdd = UserMembershipAddView()
        stackView.addArrangedSubview(membershipAdd)
        membershipAdd.translatesAutoresizingMaskIntoConstraints = false
        membershipAdd.widthAnchor.constraint(equalToConstant: 80).isActive = true
        membershipAdd.topAnchor.constraint(equalTo: stackView.topAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 定位权限
        if CLLocationManager.authorizationStatus() == .notDetermined {
            locationManager.requestAlwaysAuthorization()
        } else if CLLocationManager.authorizationStatus() == .denied {
            self.showAlert(title: "开启位置关联自动化需要开启定位功能，请从手机<设置>开启App的定位权限")
        } else if CLLocationManager.authorizationStatus() == .authorizedAlways {
            locationManager.startUpdatingLocation()
        }
    }
    
    // 设置地理围栏
    func setUpData() {
        if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
            showAlert(title: "系统不支持特定位置监听功能")
            return
        }
        
        for object in self.locationManager.monitoredRegions {
            print("ranged beacon constraints: \(object.identifier)")
        }
        
       // 家庭位置进入与离开监听
        let coordinate = CLLocationCoordinate2DMake(+22.56589379, +113.87822158)
        let regionRadius = 150.0
        let region = CLCircularRegion(center: coordinate, radius: regionRadius, identifier: self.userRegionIdentifier)
        region.notifyOnExit = true
        region.notifyOnEntry = true
        locationManager.startMonitoring(for: region)
        
        // 标记家庭位置
        let annotation = MKPointAnnotation()
        annotation.coordinate = coordinate.toEarth()
        annotation.title = self.userRegionName
        mapView.addAnnotation(annotation)
        print("rect: \(mapView.annotationVisibleRect)")

        let circle = MKCircle(center: coordinate.toEarth(), radius: regionRadius)
        mapView.addOverlay(circle)
    }
}

extension UserHomeController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let circleRender = MKCircleRenderer(overlay: overlay)
        circleRender.fillColor = UIColor(hex: "33ABA3", alpha: 0.5)
        circleRender.strokeColor = UIColor.white
        circleRender.lineWidth = 1.0
        return circleRender
    }
}

extension UserHomeController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        LocationManager.postMemberState(membership: Account.instance.membership, home: HomeManager.instance.current!.id, state: .arrive)
    }
    
    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        LocationManager.postMemberState(membership: Account.instance.membership, home: HomeManager.instance.current!.id, state: .leave)
        monitoredRegions[region.identifier] = Date()
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // 当前位置
        print("location: \(locations[0].description)")
        let userLocation:CLLocation = locations[0] as CLLocation
        locationManager.stopUpdatingLocation()
        let location = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
        let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
        let region = MKCoordinateRegion(center: location.toEarth(), span: span)
        mapView.setRegion(region, animated: true)
    }
}

extension UserHomeController {
    // 提示窗口
    func showAlert(title: String) {
        let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确认", style: .default, handler: { (action) in
            alert.dismiss(animated: true, completion: nil)
        }))
        self.present(alert, animated: true, completion: nil)
    }
}


// MARK: - 家庭成员信息视图
class UserInfoView: UIView {
    
    init(name: String, head: String, state: String = "") {
        super.init(frame: .zero)
        
        let headerView = UIImageView(image: UIImage(named: head))
        self.addSubview(headerView)
        headerView.translatesAutoresizingMaskIntoConstraints = false
        headerView.heightAnchor.constraint(equalToConstant: 64).isActive = true
        headerView.widthAnchor.constraint(equalToConstant: 64).isActive = true
        headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        headerView.layer.cornerRadius = 32
        headerView.layer.masksToBounds = true
        
        
        let nameLabel = UILabel()
        self.addSubview(nameLabel)
        nameLabel.attributedText = NSAttributedString(string: name, attributes:
            [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),
                NSAttributedString.Key.foregroundColor: UIColor.black,
                NSAttributedString.Key.kern: -0.39
            ])
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true
        nameLabel.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 8).isActive = true
        nameLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        nameLabel.textAlignment = .center
        
        if state != "" {
            let stateLabel = UILabel()
            self.addSubview(stateLabel)
            stateLabel.attributedText = NSAttributedString(string: state, attributes:
                [
                    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),
                    NSAttributedString.Key.foregroundColor: UIColor.black,
                    NSAttributedString.Key.kern: -0.39
                ])
            stateLabel.translatesAutoresizingMaskIntoConstraints = false
            stateLabel.heightAnchor.constraint(equalToConstant: 18).isActive = true
            stateLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 2).isActive = true
            stateLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
            stateLabel.textAlignment = .center
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// 添加家庭成员视图
fileprivate class UserMembershipAddView: UIView {
    init() {
        super.init(frame: .zero)
        
        let headerView = UIImageView(image: UIImage(named: "user-icon-member-add"))
        self.addSubview(headerView)
        headerView.translatesAutoresizingMaskIntoConstraints = false
        headerView.heightAnchor.constraint(equalToConstant: 64).isActive = true
        headerView.widthAnchor.constraint(equalToConstant: 64).isActive = true
        headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        headerView.layer.cornerRadius = 32
        headerView.layer.masksToBounds = true
        
        
        let nameLabel = UILabel()
        self.addSubview(nameLabel)
        nameLabel.attributedText = NSAttributedString(string: "添加成员", attributes:
            [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),
                NSAttributedString.Key.foregroundColor: UIColor(hex: "828282"),
                NSAttributedString.Key.kern: -0.39
            ])
        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true
        nameLabel.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 8).isActive = true
        nameLabel.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        nameLabel.textAlignment = .center
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


